from aioredis import Redis
from peewee_async import Manager

from cache.base import Cache


class Service:
    CACHE_CLS = Cache
    factory = {}

    def __new__(cls, *args, **kwargs):
        if not kwargs:
            mgw = args[0]
            redis = args[1]
        elif not args:
            mgw = kwargs.get("mgw")
            redis = kwargs.get("redis")
        else:
            mgw = args[0]
            redis = kwargs.get("redis")
        id_k = f"{id(mgw)}_{id(redis)}"
        key = f"{cls.__name__}_{id_k}"
        if key in cls.factory:
            return cls.factory[key]
        o = super().__new__(cls)
        cls.factory[key] = o
        return o

    def __init__(self, mgw: Manager, redis: Redis):
        self._mgw = mgw
        self._redis = redis
        self._cache = None

    @property
    def mgw(self):
        return self._mgw

    @property
    def redis(self):
        return self._redis

    @property
    def cache(self):
        if self._cache is None:
            self._cache = self.CACHE_CLS(self.redis)
        return self._cache

    async def exist(self, model, field_to_value_dict):
        return await model.exist(self.mgw, field_to_value_dict)
